package com.cksys.achievement.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cksys.achievement.entity.Result;
import com.cksys.achievement.entity.Type;
import com.cksys.achievement.mapper.TypeMapper;
import com.cksys.achievement.service.IResultPictureService;
import com.cksys.achievement.service.IResultService;
import com.cksys.achievement.service.IResultUserService;
import com.cksys.achievement.service.ITypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author tadechen
 * @since 2019-09-26
 */
@Service
public class TypeServiceImpl extends ServiceImpl<TypeMapper, Type> implements ITypeService {

    @Autowired
    TypeMapper typeMapper;

    @Autowired
    IResultService resultService;

    @Autowired
    IResultPictureService resultPictureService;

    @Autowired
    IResultUserService resultUserService;

    @Override
    public Type findTypeByName(String name) {
        return typeMapper.selectOne(new QueryWrapper<Type>().eq("name", name));
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public boolean deleteType(Integer id) {
        int delete = typeMapper.delete(new LambdaQueryWrapper<Type>().eq(Type::getId, id));
        if (delete > 0) {
            List<Result> list = resultService
                    .list(new LambdaQueryWrapper<Result>().eq(Result::getTypeId, id))
                    .stream()
                    .map(t -> t.setTypeId(0))
                    .collect(Collectors.toList());
            boolean b = true;
            if (!list.isEmpty()) {
                b = resultService.updateBatchById(list);
            }
            return b;
        }
        return false;
    }
}
